package nl.hr.cmi.project4.inf1m.groep1.ZuinigRijden;

import java.util.ArrayList;

import android.app.Activity;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.widget.ImageView;

public class Stoplicht{
	
	public static final int UIT = -1;
    public static final int ROOD = 0;
    public static final int ORANJE = 1;
    public static final int GROEN = 2;
	
    private int status;
    
    private	static ImageView imageView;
    private static Drawable imageUit;
    private static Drawable imageGroen;
    private static Drawable imageOranje;
    private static Drawable imageRood;
    
	private static final int ROOD_LIMIT = 3000;
    private static final int ORANJE_LIMIT = 2000;
    private static final int GROEN_LIMIT = 500;
    
    //Constructor plaatst in de variable image een pointer naar de ImageView image in main.xml.
    public Stoplicht(ImageView image, Activity activity){
    	imageView = image;
    	Resources resources = activity.getResources();
    	imageGroen = resources.getDrawable(R.drawable.stoplicht_groen_middel);
    	imageOranje = resources.getDrawable(R.drawable.stoplicht_oranje_middel);
    	imageRood = resources.getDrawable(R.drawable.stoplicht_rood_middel);
    	imageUit = resources.getDrawable(R.drawable.stoplicht_uit_middel);
    	setOranje();
    }
    
    public int getStatus(){
    	return status;
    }
	
    //methode voor het berekenen van stoplichtkleur.
	public void bereken(ArrayList<SmallLocation> locationList){
		int[] speeds;
		if(locationList.size() < 20){
			speeds = new int[locationList.size()];
		} else {
			speeds = new int[20];
		}
		for(int i = 1;i < speeds.length;++i){
			speeds[i] = (int)locationList.get(locationList.size() - i).getSpeed();
		}
		double sd = standaarddeviatie(speeds);
		if(sd < GROEN_LIMIT){
			setRood();
		} else if (sd < ORANJE_LIMIT){
			setOranje();
		} else if (sd > ORANJE_LIMIT){
			setRood();
		}
	}
	
	//setMethodes voor kleur stoplicht.
	public void setGroen(){
		imageView.setImageDrawable(imageGroen);
		status = GROEN;
	}
	public void setOranje(){
		imageView.setImageDrawable(imageOranje);
		status = ORANJE;
	}
	public void setRood(){
		imageView.setImageDrawable(imageRood);
		status = ROOD;
	}
	public void setUit(){
		imageView.setImageDrawable(imageUit);
		status = UIT;
	}
	
	public double variantie(int[] array){
		double result = 0.0;
		double gem = gemiddelde(array);
		for(int i = 0;i < array.length;i++){
			result += Math.pow(array[i] - gem,2);
		}
		return ((1.0/array.length)*result);
	}
	public double standaarddeviatie(int[] array){
		return Math.sqrt(variantie(array));
	}
	public double gemiddelde(int[] array){
		double som = 0;
		for(int i = 0;i < array.length;i++){
			som += array[i];
		}
		return (som / array.length);
	}
}
